using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Windows.Forms;
using Work.API.Dtos.DrugManagement;
using Work.ErrorCode;

namespace WinFormsApp1.DrugManagement
{
    /// <summary>
    /// 查看已发药品窗体（用于查看已发药品模块）
    /// 功能：
    /// 1. 显示已发放给患者的药品历史记录
    /// 2. 支持按时间筛选（今天/本周/本月/今年/全部）
    /// 3. 显示患者信息（卡号、姓名、性别、年龄、身份证号）
    /// 
    /// 注意：需要在Designer中添加控件，详见"前端窗体控件说明.md"
    /// </summary>
    public partial class DispensedDrugsForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private List<DispensedDrugDto> _dispensedDrugs;

        public DispensedDrugsForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _dispensedDrugs = new List<DispensedDrugDto>();

            // 初始化时间筛选选项
            InitializeTimeFilter();
            LoadDispensedDrugs("全部");
        }

        /// <summary>
        /// 初始化时间筛选选项
        /// </summary>
        private void InitializeTimeFilter()
        {
            // 默认选择"全部"
            if (rbAll != null)
            {
                rbAll.Checked = true;
            }
        }

        /// <summary>
        /// 加载已发药品列表
        /// </summary>
        private async void LoadDispensedDrugs(string timeFilterType)
        {
            try
            {
                var cardNumber = txtCardNumber.Text?.Trim();
                var patientName = txtPatientName.Text?.Trim();
                var drugName = txtDrugName.Text?.Trim();

                var url = $"api/Drug/GetDispensedDrugs?timeFilterType={Uri.EscapeDataString(timeFilterType)}";

                if (!string.IsNullOrWhiteSpace(cardNumber))
                    url += $"&cardNumber={Uri.EscapeDataString(cardNumber)}";
                if (!string.IsNullOrWhiteSpace(patientName))
                    url += $"&patientName={Uri.EscapeDataString(patientName)}";
                if (!string.IsNullOrWhiteSpace(drugName))
                    url += $"&drugName={Uri.EscapeDataString(drugName)}";

                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DispensedDrugDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _dispensedDrugs = apiResult.Data;
                    RefreshDataGridView();
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "查询失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载已发药品列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新数据表格
        /// </summary>
        private void RefreshDataGridView()
        {
            if (dgvDispensedDrugs != null)
            {
                // 添加DataError事件处理（如果还没有添加）
                dgvDispensedDrugs.DataError -= DgvDispensedDrugs_DataError;
                dgvDispensedDrugs.DataError += DgvDispensedDrugs_DataError;
                
                dgvDispensedDrugs.DataSource = null;
                dgvDispensedDrugs.DataSource = _dispensedDrugs;
                SetDispensedColumnHeaders(dgvDispensedDrugs);
            }
        }

        /// <summary>
        /// 设置已发药品表格的中文列标题
        /// </summary>
        private void SetDispensedColumnHeaders(DataGridView dgv)
        {
            if (dgv.Columns.Count > 0)
            {
                var columnHeaders = new Dictionary<string, string>
                {
                    { "OutboundId", "出库记录ID" },
                    { "DrugId", "药品ID" },
                    { "DrugName", "药品名称" },
                    { "CardNumber", "卡号" },
                    { "PatientName", "患者姓名" },
                    { "Gender", "性别" },
                    { "GenderText", "性别" },
                    { "Age", "年龄" },
                    { "IdCard", "身份证号" },
                    { "Quantity", "出库数量" },
                    { "UnitPrice", "出库单价" },
                    { "TotalAmount", "出库总金额" },
                    { "OutboundDate", "出库日期" },
                    { "Operator", "操作人" }
                };

                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    if (columnHeaders.ContainsKey(column.Name))
                    {
                        column.HeaderText = columnHeaders[column.Name];
                    }
                    
                    // 格式化出库单价和总金额为两位小数
                    if (column.Name == "UnitPrice" || column.Name == "TotalAmount")
                    {
                        column.DefaultCellStyle.Format = "F2";
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    }
                    
                    // 将Gender列的true/false转换为中文
                    if (column.Name == "Gender")
                    {
                        column.DefaultCellStyle.Format = "";
                        // 移除已有的事件处理器，避免重复绑定
                        dgv.CellFormatting -= DgvDispensedDrugs_GenderFormatting;
                        dgv.CellFormatting += DgvDispensedDrugs_GenderFormatting;
                    }
                }
            }
        }

        /// <summary>
        /// 已发药品列表Gender列的格式化事件
        /// </summary>
        private void DgvDispensedDrugs_GenderFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                if (sender is DataGridView dgv && e.ColumnIndex >= 0 && e.ColumnIndex < dgv.Columns.Count && dgv.Columns[e.ColumnIndex].Name == "Gender")
                {
                    // 处理bool类型
                    if (e.Value is bool boolValue)
                    {
                        e.Value = boolValue ? "男" : "女";
                        e.FormattingApplied = true;
                        return;
                    }
                    
                    // 处理可空bool类型
                    if (e.Value != null && e.Value is bool?)
                    {
                        bool? nullableBool = e.Value as bool?;
                        if (nullableBool.HasValue)
                        {
                            e.Value = nullableBool.Value ? "男" : "女";
                            e.FormattingApplied = true;
                            return;
                        }
                    }
                    
                    // 处理字符串类型（可能已经是格式化后的值，如GenderText）
                    if (e.Value is string)
                    {
                        // 已经是字符串，不需要格式化
                        e.FormattingApplied = false;
                        return;
                    }
                }
            }
            catch
            {
                // 忽略格式化错误，使用默认显示
                e.FormattingApplied = false;
            }
        }

        /// <summary>
        /// DataGridView数据错误事件处理
        /// </summary>
        private void DgvDispensedDrugs_DataError(object? sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略数据错误，避免显示默认错误对话框
            e.ThrowException = false;
        }

        /// <summary>
        /// 时间筛选选项改变
        /// </summary>
        private void TimeFilter_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton? rb = sender as RadioButton;
            if (rb != null && rb.Checked)
            {
                string timeFilterType = rb.Text;
                LoadDispensedDrugs(timeFilterType);
            }
        }

        /// <summary>
        /// 搜索已发药品
        /// </summary>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string timeFilterType = "全部";
            if (rbToday?.Checked == true) timeFilterType = "今天";
            else if (rbThisWeek?.Checked == true) timeFilterType = "本周";
            else if (rbThisMonth?.Checked == true) timeFilterType = "本月";
            else if (rbThisYear?.Checked == true) timeFilterType = "今年";

            LoadDispensedDrugs(timeFilterType);
        }

        /// <summary>
        /// 显示全部已发药品
        /// </summary>
        private void btnShowAll_Click(object sender, EventArgs e)
        {
            // 清空搜索条件
            txtCardNumber.Text = "";
            txtPatientName.Text = "";
            txtDrugName.Text = "";

            LoadDispensedDrugs("全部");
        }

        /// <summary>
        /// 清除搜索条件
        /// </summary>
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtCardNumber.Text = "";
            txtPatientName.Text = "";
            txtDrugName.Text = "";
        }
    }
}

